package com.yuxin.tongyi.lsll.thread;

import java.util.List;

import android.content.Context;

import com.yuxin.tongyi.lsll.common.Constants;
import com.yuxin.tongyi.lsll.main.LoginActivity;
import com.yuxin.tongyi.lsll.pojo.ClassInfo;
import com.yuxin.tongyi.lsll.pojo.LoginInfo;
import com.yuxin.tongyi.lsll.util.FileTool;
import com.yuxin.tongyi.lsll.util.HttpRequestUtil;
import com.yuxin.tongyi.lsll.util.PubUtil;

/**
 * @author ww
 * @date:2012-4-7 上午10:38:42
 * @Desc: 获取服务器班级信息并保存本地
 * @version :
 * 
 */
public class SaveClassDataThread implements Runnable {

	private Context context;
	private HttpRequestUtil request;
	private LoginInfo loginInfo;
	
	public SaveClassDataThread(Context context, LoginInfo loginInfo){
		this.context = context;
		this.loginInfo = loginInfo;
		
		request = new HttpRequestUtil();
	}
	
	@Override
	public void run() {
		try{
			boolean flag = request.classListRequest(loginInfo.getLoginName(), loginInfo.getPassword()); // 请求班级列表
			String status = request.getStatus();
			if (flag) {// 服务器响应
				if (status != null && !"".equals(status)) {
					List<Object> objects = request.getObjList();
					if (objects != null && objects.size() > 0) { // 服务器正确响应数据
						Object obj = objects.get(0);
						if (obj instanceof ClassInfo) {
							ClassInfo info = (ClassInfo) obj;
							//第一个班级
							String firstClass = FileTool.getObjectToString(info.getClassObj().get(0));
							//将对象转换成对象流，然后通过SharedPreferences保存
							String classInfo = FileTool.getObjectToString(info);
							//保存请求班级状态和数据
							PubUtil.setConfigValue(context, Constants.CFG_CLASS_DATA, classInfo);
							PubUtil.setConfigValue(context, Constants.CFG_CLASS_STATE, Constants.TH_CLASS_ON);
							PubUtil.setConfigValue(context, Constants.CFG_CLASS_FIRST, firstClass);
						}
					} else { 
						// 暂无数据
						PubUtil.setConfigValue(context, Constants.CFG_CLASS_STATE, Constants.TH_CLASS_EMPTY);
					}
				} else {
					PubUtil.setConfigValue(context, Constants.CFG_CLASS_STATE, Constants.TH_CLASS_ERROR);
				}
			} else { // 访问服务器失败
				PubUtil.setConfigValue(context, Constants.CFG_CLASS_STATE, Constants.TH_CLASS_OFF);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
